import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { DNavBar, DModal, DPaymodel } from '@/components'
import DHeader from './component/header'
import DContent from './component/content'
import DList from './component/list'
import DFooter from './component/footer'
import classNames from 'classnames'
import http from '@/api'
import sdk from '@/common/sdk'
import dayjs from 'dayjs'
import './itemdetail.scss'
const getUrlScheme = http.getUrlScheme

class DShopdetail extends Component {

  constructor(props) {
    super(props)
    this.state = {
      bgImages: require('../assets/bgImages.png'),
      title: "购车订单",
      headerobj: {
        itemtime: {
          isShowDay: false,
          isShowHour: true,
          day: 0,
          hours: 0,
          minutes: 0,
          seconds: 0
        },
      },
      isShow: false,
      isDelay: false,
      item: {},
      count: 0,

      firstList: {
        info: [
          {
            label: "卖家名称",
            value: ""
          },
          {
            label: "卖家联系人",
            value: ""
          },
          {
            label: "卖家联系方式",
            value: ""
          }
        ]
      },
      status: '',
      secondList: {
        title: "车辆信息",
        info: [
          {
            label: "交易车型",
            value: ""
          },
          {
            label: "车源类型",
            value: ""
          },
          {
            label: "车辆指导价",
            value: ""
          },
          {
            label: "外观颜色",
            value: ""
          },
          {
            label: "内饰颜色",
            value: ""
          },
          {
            label: "排放标准",
            value: ""
          },
          // {
          //   label: "手续",
          //   value: ""
          // },
        ]
      },
      threeList: {
        title: "交易信息",
        info: [
          {
            label: "成交数量",
            value: ""
          },
          {
            label: "成交总价",
            value: ""
          },
          {
            label: "订金金额",
            value: ""
          },
          {
            label: "卖方银行卡",
            value: ""
          }
        ]
      },
      dlist: {
        list: [
          {
            title: '合同凭证'
          }
        ]
      }
    }
  }

  componentWillMount() {
    let { id, status } = this.$router.params
    if (window.localStorage.getItem('ISPAY')) {
      // this.state.isOpened： = true
      this.setState({
        isOpened: true
      }, () => window.localStorage.removeItem('ISPAY'))
    }
    this.setState({
      status,
      headerobj: {
        ...this.state.headerobj,
        title: this.getStatus(status)
      }
    })
    this.getDetailList(id)

  }

  componentDidShow() {
    sdk.setTitleInfo(this.state.title)
  }


  getStatus(status) {
    return {
      $11: `待支付`,
      $21: `待卖家接单`,
      $31: `待卖家上传`,
      $32: `待确认`,
      $33: `待核实`,
      $41: `交易成功`,
      $42: `拒绝接单`,
      $43: `已撤回`,
      $44: `已超时`,
      $45: `交易异常`,
      $49: `待退款`
    }[`$${status}`]
  }
  getDetailList(id) {
    let { firstList, secondList, threeList } = this.state
    http.getSaleDetail(id).then(res => {
      if (!res) {
        return
      }
      if (res.orStatus !== this.$router.params.status) {
        Taro.showToast({
          title: '订单状态已更新',
          icon: 'none'
        }).then(date => {
          Taro.redirectTo({
            url: `/pages/itemdetail/shopdetail?id=${res.id}&status=${res.orStatus}`
          })
        })
      }
      // 单位配对
      function getPrice(i) {
        return {
          $0: '台',
          $1: '万元',
          $2: '元'
        }[`$${i}`]
      }
      let _firstList = ['orSaleComp', 'orSale', 'orSaleContact'] //
      firstList.info.map((item, i) => {
        item.value = res[_firstList[i]]
      })

      let _secondList = ['orCarModel', 'orCarSourceType', 'orCarGuiPrice', 'orCarOutColor', 'orCarInColor', 'orCarEmissionStd',]
      secondList.info.map((item, i) => {
        item.value = res[_secondList[i]] + (i === 2 ? getPrice(1) : '')
      })

      let _threeList = ['orCount', 'orTotalPrice', 'orEarnestPrice', 'bankNo']
      threeList.info.map((item, i) => {
        item.value = res[_threeList[i]] + getPrice(i)
      })

      //根据订单状态计算倒计时
      let orStatus = this.$router.params.status
      let times = ''
      if (orStatus === '21') {
        let createTime = dayjs(res.createTime).add(30, 'minute')
        times = createTime.diff(dayjs(), 'day', 'true')
      } else if (orStatus === '32') {
        let createTime = dayjs(res.updateTime).add(3, 'day')
        times = createTime.diff(dayjs(), 'day', 'true')
      } else {
        times = 0
      }
      this.setState({
        firstList,
        secondList,
        threeList,
        item: res,
        count: res.orIsDelay,
        headerobj: {
          ...this.state.headerobj,
          account: res.orNo,
          text: this.getText(orStatus),
          tiptext: this.getPlatformTxt(orStatus),
          itemtime: {
            isShowDay: false,
            isShowHour: true,
            day: times,
            hours: 0,
            minutes: 0,
            seconds: 0
          }
        }
      })
      // debugger
    })
  }
  getPlatformTxt(orstatu) {
    return {
      $11: '系统将自动取消订单',
      $21: '系统将自动取消订单',
      $31: '请耐心等候',
      $32: '系统将自动确认',
      // $33: '将自动确认',
    }[`$${orstatu}`]
  }
  //确认合同
  onConfirmContract() {
    let { item } = this.state
    Taro.redirectTo({
      url: `/pages/contractproof/contractproof?id=${item.id}`
    })
  }
  //延期合同
  onDelayConfirm() {
    let { count } = this.state
    if (count === '1') {
      return Taro.showToast({
        title: '您已延期过一次，不可再次操作',
        icon: 'none'
      })
    }
    this.setState({
      isDelay: true
    })
  }
  getText(orstatu) {
    return {
      $11: '请支付订金',
      $21: '请等待卖家接单',
      $31: '交易完成后，卖家将上传资料',
      $32: '请确认卖家所上传的合同',
      $33: `平台将在<text style='font-size:20px;font-weight:bold;color:#FFAE00'>5</text>日内核实订单，逾时将自动确认`,
      $41: '亲，恭喜你成功完成一笔订单！',
      $42: '很遗憾，卖家拒接该订单',
      $44: '该订单已超时',
      $43: '您已取消该订单',
      $45: '您的订单交易异常，平台客服已介入并终止',
      $49: '该订单退款中，请等待卖家确认',
    }[`$${orstatu}`]
  }

  delayConfirmOrder(orderId) {
    http.delayConfirmOrder({ orderId: orderId }).then(res => {
      let createTime = dayjs(res.updateTime).add(3, 'day')
      let times = createTime.diff(dayjs(), 'day', 'true')
      let { headerobj } = this.state
      let { itemtime } = headerobj
      itemtime.day = times
      this.setState({
        count: res.orIsDelay,
        headerobj: {
          ...headerobj,
          itemtime
        }
      })
    })
  }
  confirmDelay() {
    this.onClose()
    let { item } = this.state
    this.delayConfirmOrder(item.id)
  }
  oncancelDelay() {
    this.onClose()
  }
  //撤回订单
  onHandleRecall() {
    this.setState({
      isShow: true
    })
  }
  drawOrder() {
    let { item } = this.state
    http.drawOrder({ orderId: `${item.id}` }).then(res => {
      Taro.redirectTo({
        url: `/pages/itemdetail/shopdetail?id=${item.id}&status=43`
      })
    })
  }

  onClose() {
    this.setState({
      isShow: false,
      isDelay: false
    })
  }
  onLastHandle() {
    this.onClose()
    this.drawOrder()
  }
  handleContact() {
    let { item } = this.state
    Taro.navigateTo({
      url: `/pages/contractproof/contractproof?id=${item.id}&status=1`
    })
  }
  //支付订金
  onHanlePay() {
    // http.getEarnestForm(params).then(res => {
    //   window.location.href = res.payUrl
    // }).catch(() => {
    //   Taro.showToast({
    //     title: '网络异常!',
    //     icon: "none"
    //   })
    // })
    this.setState({
      ispayShow: true,
    })
    // this.onCancelPay()
  }
  payFuc(type) {
    this.setState({
      isOpened: false
    })
    if (type) {
      Taro.redirectTo({
        url: `/pages/shoporders/shoporders?active=1`
      })
    }
  }
  handleClose() {
    this.setState({
      ispayShow: false
    })
  }
  async onCancelPay(payType = '1') {
    let { item } = this.state
    if (payType == 8) {
      const url = await getUrlScheme(item.id, 0)
      window.location.href = url
      return
    }
    http.transCaPayOrder({ id: item.id, payIp: window.payIp, payType }).then(res => {

      setTimeout(() => {

        // Taro.navigateBack({
        //     delta: 2
        // })
        // window.localStorage.setItem('ISPAY',1)
        if (+payType === 1) {
          if (!res.payUrl) {
            return Taro.showToast({
              title: '订单状态异常',
              icon: 'none'
            })
          }
          window.location.href = res.payUrl
        }
        if (payType == 7) {
          let url = encodeURIComponent(res.payUrl)
          return Taro.navigateTo({
            url: `/pages/wxQrCode?payUrl=${url}`
          })
        }

        // Taro.redirectTo({
        //     url: `/pages/shoporders/shoporders?active=1`
        // })
      }, 500)

    })
  }
  render() {
    const {
      bgImages,
      title,
      firstList,
      secondList,
      threeList,
      headerobj,
      isShow,
      isDelay,
      status,
      dlist
    } = this.state
    return (
      <View className='b_itemdetail'>
        <Image src={bgImages} className={classNames('b_itemdetail__imagebs', process.env.NODE_ENV === 'development' ? '' : 'b_itemdetail__NODEimg')}></Image>
        <DNavBar title={title} className='b_itemdetail__nav'></DNavBar>
        <View className='b_itemdetail__box'>
          <View className='b_itemdetail__content'>
            <DHeader {...headerobj}></DHeader>
            <DContent {...firstList}></DContent>
            <DContent {...secondList}></DContent>
            <DContent {...threeList}></DContent>
            {status > 32 && status < 42 &&
              <DList {...dlist} handleClick={this.handleContact.bind(this)}></DList>
            }
            {status === '11' &&
              <DFooter firstText='支付订金' onFirstClick={this.onHanlePay.bind(this)} ></DFooter>
            }
            {status === '21' &&
              <DFooter firstText='撤回订单' onFirstClick={this.onHandleRecall.bind(this)} ></DFooter>
            }
            {status === '32' &&
              <DFooter firstText='延期确认' onFirstClick={this.onDelayConfirm.bind(this)} secondText='确认合同' onSeconClick={this.onConfirmContract.bind(this)}></DFooter>
            }
          </View>
        </View>
        <DModal
          isShow={isShow}
          title='提示'
          text='确定要撤回订单吗？'
          firstbtn='取消'
          lastbtn='撤回'
          onFirst={this.onClose.bind(this)}
          onCancel={this.onClose.bind(this)}
          onLast={this.onLastHandle.bind(this)}
        ></DModal>
        <DModal
          isShow={isDelay}
          title='提示'
          text='您是否确认进行延期确认操作？可延期三天确认交易完成，仅可延期一次'
          firstbtn='取消'
          lastbtn='延期'
          onFirst={this.oncancelDelay.bind(this)}
          onCancel={this.onClose.bind(this)}
          onLast={this.confirmDelay.bind(this)}
        ></DModal>
        <DModal isShow={this.state.isOpened} title="支付提示" text="是否已完成支付？" firstbtn="支付失败" lastbtn="支付完成" onFirst={this.payFuc.bind(this)} onCancel={this.payFuc.bind(this)} onLast={this.payFuc.bind(this, 1)}></DModal>
        <DPaymodel handleClose={this.handleClose.bind(this)} onCancel={this.onCancelPay.bind(this)} isShow={this.state.ispayShow} />
      </View>
    )
  }

}
export default DShopdetail
